<template>
  <view class="page-container">
    <view class="page-top">
      <up-tabs :list="tabs" :lineWidth="40" @click="tabsClick"><!--重置数据，并触发刷新-->
      </up-tabs>
    </view>
    <!--分割线-->
    <up-line></up-line>
    <!-- 列表展示 -->
    <scroll-view class="room-list" :scroll-y="true" :refresher-enabled="true" :refresher-triggered="triggered"
                 @refresherpulling="onPull" @refresherrefresh="onRefresh" @refresherrestore="onRestore"
                 @refresherabort="onAbort" @scrolltolower="onTolower">
      <view v-for="room in roomList" :key="room.roomId" class="room-card">
        <!-- 房间卡片 -->
        <view class="room-card-header">
          <text class="room-id">房间号: {{ room.roomId }}</text>
          <text class="room-time">{{ room.createDate }}</text>
        </view>

        <!-- 房间参与者头像 -->
        <view class="participants">
          <view v-for="user in room.roomUsers" :key="user.userId" class="participant-avatar">
            <!-- 头像 -->
            <view class="avatar-container">
              <image :src="proxy.$tool.getResources(user.avatar)" mode="aspectFill" class="avatar">
              </image>
              <!-- 如果是房主，显示小皇冠 -->
              <image v-if="user.isHost===0" src="/static/owner.png" class="owner-icon"></image>
            </view>

            <!-- 每个人的得分 -->
            <text class="positive" v-if="user.score>0">{{ user.score }}</text>
            <text class="negative" v-else>{{ user.score }}</text>
          </view>
        </view>

        <!-- 房间详情按钮 -->
        <view class="room-footer">
          <button class="detail-btn" @click="openResult(room)" v-if="room.isStart===2">
            <text>查看结果</text>
          </button>
          <button class="detail-btn" @click="viewRoomDetail(room)" v-else>
            <text>进入房间</text>
          </button>
        </view>
      </view>
    </scroll-view>
    <authPopup ref="authPopupRef" @ok="findRoomByPage()"></authPopup>
    <resultPopup ref="resultPopupRef"></resultPopup>
  </view>
</template>

<script setup>
import {
  ref,
  computed,
  getCurrentInstance,
} from "vue";
import {
  useStore
} from "vuex";
import {
  onShow
} from "@dcloudio/uni-app";
import authPopup from "@/components/authPopup";
import resultPopup from "@/components/resultPopup";

const {
  proxy
} = getCurrentInstance();
const store = useStore();

//定义认证弹出ref
const authPopupRef = ref(null)
//定义比赛结果弹框ref
const resultPopupRef = ref(null)

//获取当前用户
const userInfo = computed(() => store.state.userInfo);

//定义房间列表
const roomList = ref([])

//定义下拉刷新状态
const triggered = ref(false)

//定义标签列表
const tabs = ref([
  {
    name: '准备中'
  },
  {
    name: '进行中'
  },
  {
    name: '已结束'
  },
])


//定义搜索参数
const searchParams = ref({
  //计分模式
  mode: "",
  //台费规则
  taiwanFee: "",
  //房间状态:0：未开始，1：进行中；2：已结束
  isStart: "0",
})

//定义分页条件
const pager = ref({
  total: 0, // 总记录数
  currentPage: 1, // 当前页数
  pageSize: 4, // 每页显示多少条
})

/**
 * 重置pager
 */
const initPager = () => {
  pager.value = {
    total: 0, // 总记录数
    currentPage: 1, // 当前页数
    pageSize: 4, // 每页显示多少条
  }
}


const tabsClick = e => {
  //重置pager
  initPager();
  searchParams.value.isStart = e.index;
  onRefresh()
}

//每次页面展示都会调用
onShow(() => {
  if (userInfo.value === null || userInfo.value === "") {
    //判断是否认证
    setTimeout(res => {
      authPopupRef.value.open();
    })
    return;
  }
  findRoomByPage();
})

/**
 * 分页查询房间
 */
const findRoomByPage = (fun, err) => {
  proxy.$request.get(`/bus-room/findStartRoomByTime`, {
    ...pager.value,
    ...searchParams.value
  }).then(res => {
    roomList.value = res.records;
    pager.value.total = res.total;
    if (fun) {
      fun();
    }
  }).catch(e => {
    if (err) {
      err()
    }
  })
}

/**
 * 下拉刷新出发
 */
const onPull = () => {
  triggered.value = true;
}

/**
 * 开始刷新数据
 */
const onRefresh = () => {
  //重置pager
  initPager();
  findRoomByPage(() => {
    triggered.value = false; // 刷新完成，复位触发状态
    uni.stopPullDownRefresh(); // 停止下拉刷新
  }, () => {
    triggered.value = false; // 刷新完成，复位触发状态
    uni.stopPullDownRefresh(); // 停止下拉刷新
  });
}

/**
 * 复位
 */
const onRestore = () => {
  triggered.value = false;
}

/**
 * 取消刷新
 */
const onAbort = () => {
  triggered.value = false;
}

/**
 *  滚动到底部
 */
const onTolower = () => {
  if (pager.value.total > roomList.value.length) {
    pager.value.pageSize = pager.value.pageSize + 4; // 重置为第一页
    findRoomByPage(() => {
      triggered.value = false; // 刷新完成，复位触发状态
      uni.stopPullDownRefresh(); // 停止下拉刷新
    }, () => {
      triggered.value = false; // 刷新完成，复位触发状态
      uni.stopPullDownRefresh(); // 停止下拉刷新
    });
  }
}

/**
 * 切换到房间列表
 */
const viewRoomDetail = room => {
  //判断房间状态
  switch (room.isStart) {
    case 0:
      //准备中的状态切换到准备页面
      uni.navigateTo({
        url: `/pages/joinRoom/joinRoom?id=${room.roomId}`
      })
      break;
    case 1:
      //进行中的状态切换到计分页面
      uni.navigateTo({
        url: `/pages/scoring/scoring?id=${room.roomId}`
      })
      break;
    case 2:
      break

  }
}

/**
 * 打开结果弹框
 */
const openResult = (item) => {
  if (item.isStart !== 2) {
    return;
  }
  resultPopupRef.value.open(item);

}

</script>
<style lang="less" scoped>
.page-container {
  height: 100vh;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 16px;
  background-color: #f5f5f5;

  .page-top {
    width: 100%;
    text-align: center;

    :deep(.u-tabs__wrapper__nav__item) {
      flex: 1 !important;
    }
  }

  .room-list {
    margin-top: 20px;
    width: 100%;
    flex: 1;
    overflow-y: scroll;

    .room-card {
      background-color: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      margin-bottom: 16px;
      padding: 16px;

      .room-card-header {
        display: flex;
        justify-content: space-between;
        margin-bottom: 8px;

        .room-id {
          font-size: 14px;
          font-weight: bold;
        }

        .room-time {
          font-size: 12px;
          color: #888;
        }
      }
    }

    .participants {
      display: flex;
      justify-content: space-around;
      margin: 12px 0;

      .participant-avatar {
        display: flex;
        flex-direction: column;
        align-items: center;

        .avatar-container {
          position: relative;
          margin-bottom: 8px;

          .owner-icon {
            position: absolute;
            top: -15px;
            right: 6px;
            width: 25px;
            height: 20px;
            border-radius: 50%;
            padding: 2px;
          }

          .avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;

          }
        }

        .positive {
          color: #4cd964;
        }

        .negative {
          color: #dd524d;
        }
      }

    }


    .room-footer {
      text-align: center;

      .detail-btn {
        background-color: #1aad19;
        color: #fff;
        padding: 8px 16px;
        border-radius: 20px;
        font-size: 14px;
      }
    }


  }

}
</style>